#include "importer.hpp"

#include <QDebug>

Importer::Importer(MemoDb *db) {
	m_db = db;
}

bool Importer::Import(QString filePath, int categoryID) {
	QFile* file= new QFile(filePath);
	if(!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
		return false;
	}
	QXmlStreamReader xml(file);
	QSharedPointer<Set> rootSet;
	while(!xml.atEnd() && !xml.hasError()){
		QXmlStreamReader::TokenType token = xml.readNext();
		if(token == QXmlStreamReader::StartDocument)
			continue;
		if(token == QXmlStreamReader::StartElement){
			if(xml.name() == "set") {
				rootSet = this->parseSet(xml);
			}
		}
		xml.readNext();
	}

	m_db->saveSet(*rootSet, categoryID);
	return true;
}

QSharedPointer<Set> Importer::parseSet(QXmlStreamReader& xml) {
	QString name;
	QString desc;
	QList<QSharedPointer<Question> > questions;
	QXmlStreamAttributes att = xml.attributes();

	if(att.hasAttribute("name"))
		name = att.value("name").toString();

	if(att.hasAttribute("desc"))
		desc = att.value("desc").toString();

	QSharedPointer<Set> set = QSharedPointer<Set>(new Set(-1, name, desc, questions));
	xml.readNext();

	while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == "set")){
		if(xml.tokenType() == QXmlStreamReader::StartElement)
		{
			if(xml.name() == "question")
				set->addQuestion(this->parseQuestion(xml));
		}
		xml.readNext();
	}
	return set;
}

QSharedPointer<Question> Importer::parseQuestion(QXmlStreamReader& xml) {
	QString text;
	QList<QSharedPointer<Answer> > answers;

	QXmlStreamAttributes att = xml.attributes();
	if(att.hasAttribute("text"))
			text = att.value("text").toString();

	QSharedPointer<Question> question = QSharedPointer<Question>(new Question(-1, text, answers));
	xml.readNext();

	while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == "question")){
		qDebug() << "\nElement type" << xml.tokenType();
		qDebug() << "\nElement name" << xml.name();
		if(xml.tokenType() == QXmlStreamReader::StartElement)
		{
			if(xml.name() == "answer")
				question->addAnswer(this->parseAnswer(xml));
		}
		xml.readNext();
	}
	return question;
}

QSharedPointer<Answer> Importer::parseAnswer(QXmlStreamReader& xml) {
	QString text;
	bool valid;

	QXmlStreamAttributes att = xml.attributes();
	if(att.hasAttribute("text"))
			text = att.value("text").toString();
	if(att.hasAttribute("valid"))
			valid = att.value("text").toString().toLower() == "true";

	return QSharedPointer<Answer>(new Answer(-1, text, valid));
}


